define([
    'angular',
    'config',
    'constants'
],function(angular,config, constants) {
    angular.module('gold.finder',[])

        .factory('$$finder',['$http','$timeout','$q',
            function($http,$timeout,$q) {
                /**
                 * @ngdoc service
                 * @name $$cherry.$$finder
                 *
                 * @description
                 * $$cherry.$finder 提供了对各种信息的查询
                 *
                 */

                var searchCarModal;
                var task;
                var printList;
                var noteQuery;

                var controlSearchTime = function(_data,keywords){
                    if(keywords.effectiveDateBegin!== undefined && keywords.effectiveDateBegin!== '')_data.effectiveDateBegin = keywords.effectiveDateBegin+' '+'00:00:00';
                    if(keywords.effectiveDateEnd!== undefined && keywords.effectiveDateEnd!== '')_data.effectiveDateEnd = keywords.effectiveDateEnd+' '+'23:59:59';
                    if(keywords.issueDateBegin!== undefined && keywords.issueDateBegin!== '')_data.issueDateBegin = keywords.issueDateBegin+' '+'00:00:00';
                    if(keywords.issueDateEnd!== undefined && keywords.issueDateEnd!== '')_data.issueDateEnd = keywords.issueDateEnd+' '+'23:59:59';
                    if(keywords.expireDateBegin!== undefined && keywords.expireDateBegin!== '')_data.expireDateBegin = keywords.expireDateBegin+' '+'00:00:00';
                    if(keywords.expireDateEnd!== undefined && keywords.expireDateEnd!== '')_data.expireDateEnd = keywords.expireDateEnd+' '+'23:59:59';
                    if(keywords.operateDateTimeBegin!== undefined && keywords.operateDateTimeBegin!== '')_data.operateDateTimeBegin = keywords.operateDateTimeBegin+' '+'00:00:00';
                    if(keywords.operateDateTimeEnd!== undefined && keywords.operateDateTimeEnd!== '')_data.operateDateTimeEnd = keywords.operateDateTimeEnd+' '+'23:59:59';

                    return _data;
                };
                return {
                    getFinder:function(keyword,show){
                        var searchConditions={};
                        var REGEX_CAR = /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$/;
                        var REGEX_PROPOSAL = /^2{1}\d{18}$/;
                        var REGEX_POLICY = /^L{1}[A-Z_0-9]{15}$/;
                        //保单
                        if(REGEX_POLICY.test(keyword)){
                            searchConditions.policyNo=keyword;
                            searchConditions.businessType='4';
                        }
                        //投保单
                        if(REGEX_PROPOSAL.test(keyword)){
                            searchConditions.proposalNo=keyword;
                            searchConditions.businessType='2';
                        }
                        //车
                        if(REGEX_CAR.test(keyword)){
                            searchConditions.plateNo=keyword;
                            searchConditions.businessType='7';
                        }
                        return searchConditions;
                    },
                    /**
                     * @ngdoc
                     * @name $$cherry.$$finder#search
                     * @methodOf $$cherry.$$finder
                     *
                     * @description
                     * 综合查询接口
                     * @example
                     * $$finder.search(target,keywords,pagination);
                     * @param
                     * {Object()} target 综合查询类型如：'customer'、'salesman'、'search'、'tax'
                     * @param
                     * {Object()} keywords 综合查询查询条件
                     * @param
                     * {Object()} pagination 综合查询列表页数和每页多少页
                     * @returns {httpPromise} resolve with fetched data, or fails with error description.
                     */
                    search: function(target,keywords,pagination) {
                        var deferred=$q.defer();
                        if(target === constants.TARGET.CUSTOMER){
                            var _data= {
                                head:{
                                    "transCode":"CustomerQuery",
                                    "transType":"Req",
                                    "token":$$user.getUser().token
                                },
                                "identifyType":keywords.identifyType=== undefined?'':keywords.identifyType,
                                "identifyNumber":keywords.identifyNumber=== undefined?'':keywords.identifyNumber,
                                "name":keywords.name=== undefined?'':keywords.name,
                                "id":keywords.id=== undefined?'':keywords.id,
                                "orgcode":keywords.orgcode=== undefined?'':keywords.orgcode,
                                "type":keywords.type=== undefined?'':keywords.type
                            };
                            $http({
                                method: 'POST',
                                dataType: "json",
                                contentType:'application/json; charset=UTF-8',
                                url: config.backend.ip + config.backend.customerQuery,
                                headers: {},
                                data:_data
                            })
                                .success(function( ){
                                    data = $$adapter.import('customers',data);
                                    deferred.resolve(data);
                                })
                                .error(function(e, code){
                                    deferred.reject(code);
                                });
                        }else if(target === constants.TARGET.SALESMAN){
                            var _data={
                                head:{
                                    "transCode":"Salesman",
                                    "transType":"Req",
                                    "token":$$user.getUser().token
                                },
                                "loginCom": $$user.getUser().comCode,
                                "conditions":keywords.conditions,
                                "queryType": keywords.queryType
                            };
                            $http({
                                method: 'POST',
                                dataType: "json",
                                contentType:'application/json; charset=UTF-8',
                                url:config.backend.ip + config.backend.handler,
                                //url: "http://10.128.20.80:9001/Channel/channelTask/channelTaskMain.do",
                                headers: {},
                                data:_data
                            })
                                .success(function(data){
                                    data = $$adapter.import('salesman',data);
                                    deferred.resolve(data);
                                })
                                .error(function(e, code){
                                    deferred.reject(code);
                                });
                        }else if(target === constants.TARGET.TAX){
                            $http({
                                method: 'POST',
                                dataType: "json",
                                contentType:'application/json; charset=UTF-8',
                                url: config.backend.ip+config.backend.taxList,
                                headers: {},
                                data:{
                                    head:{
                                        "transCode": "PayNoQuery",
                                        "transType": "Req",
                                        "token": $$user.getUser().token
                                    },
                                    "rows":pagination.rows=== undefined?'':pagination.rows,
                                    "pageNo":pagination.pageNo=== undefined?'':pagination.pageNo,
                                    "comCode": $$user.getUser().comCode,
                                    "department": keywords.department===undefined?'':keywords.department,
                                    "payNo": keywords.payNo===undefined?'':keywords.payNo,
                                    "plateNo": keywords.plateNo===undefined?'':keywords.plateNo,
                                    "policyNo": keywords.policyNo===undefined?'':keywords.policyNo,
                                    "payId": keywords.payId===undefined?'':keywords.payId,
                                    "taxStartDate": keywords.taxStartDate===undefined?'':keywords.taxStartDate+' 00:00:00',
                                    "taxEndDate": keywords.taxEndDate===undefined?'':keywords.taxEndDate+' 23:59:59',
                                    "loginCom": $$user.getUser().comCode
                                }
                            })
                                .success(function(data){
                                    data = $$adapter.import('tax',data);
                                    deferred.resolve(data);
                                })
                                .error(function(e, code){
                                    deferred.reject(code);
                                });
                        }else if(target === constants.TARGET.SEARCH){
                            var _data={
                                "head": {
                                    "token":$$user.getUser().token,
                                    "transType": "Req"
                                },
                                "loginCom":$$user.getUser().comCode,
                                "rows":pagination.pageSize=== undefined?'':pagination.pageSize,
                                "pageNo":pagination.pageIndex=== undefined?'':pagination.pageIndex,
                                "businessType": keywords.businessType=== undefined?'':keywords.businessType,
                                "policyNo": keywords.policyNo=== undefined?'':keywords.policyNo,
                                "endorseNo": keywords.endorseNo=== undefined?'':keywords.endorseNo,
                                "insuredName": keywords.insuredName=== undefined?'':keywords.insuredName,
                                "queryStatus": keywords.queryStatus=== undefined?[]:keywords.queryStatus
                            };
                            _data.head.transCode = "FindBusinesses",
                                _data.vIN = keywords.vIN=== undefined?'':keywords.vIN,
                                _data.adjustPermitDate= keywords.adjustPermitDate=== undefined?'':keywords.adjustPermitDate,
                                _data.applicantIdentifyNumber = keywords.applicantIdentifyNumber=== undefined?'':keywords.applicantIdentifyNumber,
                                _data.engine = keywords.engine=== undefined?'':keywords.engine,
                                _data.insuredIdentifyNumber = keywords.insuredIdentifyNumber=== undefined?'':keywords.insuredIdentifyNumber,
                                _data.isInterimStorage = keywords.isInterimStorage=== undefined?'':keywords.isInterimStorage,
                                _data.plateNo = keywords.plateNo=== undefined?'':keywords.plateNo,
                                _data.proposalName = keywords.proposalName=== undefined?'':keywords.proposalName,
                                _data.operatorCode = keywords.operatorCode=== undefined?'':keywords.operatorCode,
                                _data.proposalNo = keywords.proposalNo=== undefined?'':keywords.proposalNo;

                            _data = controlSearchTime(_data,keywords);

                            keywords = keywords || {};
                            $http({
                                method: 'POST',
                                dataType: "json",
                                contentType:'application/json; charset=UTF-8',
                                url: config.backend.ip + config.backend.search,
                                headers: {},
                                data : _data
                            })
                                .success(function(data) {
                                    data = $$adapter.import('search',data);
                                    deferred.resolve(data);
                                })
                                .error(function(e, code) {
                                    deferred.reject(code);
                                });
                        }
                        return deferred.promise;
                    },
                    /**
                     * @ngdoc
                     * @name $$cherry.$$finder#discard
                     * @methodOf $$cherry.$$finder
                     *
                     * @description
                     * 单证作废接口
                     * @example
                     * $$finder.BusinessVoid(keywords,proposalSearch);
                     * @param
                     * {Object()} keywords 作废接口businessType参数
                     * @param
                     * {Object()} proposalSearch 作废接口businessNo参数
                     * @returns {httpPromise} resolve with fetched data, or fails with error description.
                     */
                    discard : function(keywords,proposalSearch){
                        var deferred=$q.defer();
                        var _data={
                            "head": {
                                "transCode": "BusinessVoid",
                                "transType": "Req",
                                "token": $$user.getUser().token
                            },
                            "userCode": $$user.getUser().userCode,
                            "loginCom": $$user.getUser().comCode,
                            "businessNo": proposalSearch.businessNo=== undefined?'':proposalSearch.businessNo,
                            "businessType":keywords=== undefined?'':keywords
                        };
                        $http({
                            method: 'POST',
                            dataType: "json",
                            contentType:'application/json; charset=UTF-8',
                            url: config.backend.ip + config.backend.businessVoid,
                            headers: {},
                            data:_data
                        })
                            .success(function(data){
                                data = $$adapter.import('discard',data);
                                deferred.resolve(data);
                            })
                            .error(function(e, code){
                                deferred.reject(code);
                            });
                        return deferred.promise;
                    },
                    /**
                     * @ngdoc
                     * @name $$cherry.$$finder#taskCount
                     * @methodOf $$cherry.$$finder
                     *
                     * @description
                     * 任务数量查询
                     * @example
                     * $$finder.taskCount(keywords);
                     * @param {Object()} keywords 任务数量查询条件
                     * @returns {httpPromise} resolve with fetched data, or fails with error description.
                     */
                    taskCount : function(keywords){
                        var deferred=$q.defer();
                        $http({
                            method: 'POST',
                            dataType: "json",
                            contentType:'application/json; charset=UTF-8',
                            url: config.backend.ip + config.backend.taskCount,
                            headers: {},
                            data:{
                                head:{
                                    "transCode":"FindTaskCount",
                                    "transType":"Req",
                                    "token":$$user.getUser().token
                                },
                                "taskType": keywords.taskType,
                                "userCode": $$user.getUser().userCode,
                                "loginCom": $$user.getUser().comCode
                            }
                        })
                            .success(function(data){
                                data = $$adapter.import('taskCount',data);
                                deferred.resolve(data);
                            })
                            .error(function(e, code){
                                deferred.reject(code);
                            });
                        return deferred.promise;
                    },
                    /**
                     * @ngdoc
                     * @name $$cherry.$$finder#task
                     * @methodOf $$cherry.$$finder
                     *
                     * @description
                     * 任务列表查询
                     * @example
                     * $$finder.task(keywords,pagination);
                     * @param {Object()} keywords 任务查询条件
                     * @param {Object()} pagination 任务查询页数和每页多少页
                     * @returns {httpPromise} resolve with fetched data, or fails with error description.
                     */
                    task : function(keywords,pagination){
                        var deferred=$q.defer();
                        $http({
                            method: 'POST',
                            dataType: "json",
                            contentType:'application/json; charset=UTF-8',
                            url: config.backend.ip + config.backend.task,
                            headers: {},
                            data:{
                                head:{
                                    "transCode":"FindTask",
                                    "transType":"Req",
                                    "token":$$user.getUser().token
                                },
                                "pageNo":pagination.pageNo=== undefined?'':pagination.pageNo,
                                "rows":pagination.rows=== undefined?'':pagination.rows,
//                                "pageNo":1,
//                                "rows":10,
                                "VIN": keywords.VIN=== undefined?'':keywords.VIN,
                                "businessType": keywords.businessType=== undefined?'':keywords.businessType,
                                "contractNo": keywords.contractNo=== undefined|| keywords.contractNo === ''?[]:angular.isArray(keywords.contractNo)?keywords.contractNo:[keywords.contractNo],
                                "fleetNo": keywords.fleetNo=== undefined?'':keywords.fleetNo,
                                "insuredName": keywords.insuredName=== undefined?'':keywords.insuredName,
                                "owners": keywords.owners=== undefined?'':keywords.owners,
                                "plateNo": keywords.plateNo=== undefined?'':keywords.plateNo,
                                "proposalName": keywords.proposalName=== undefined?'':keywords.proposalName,
                                "taskArchiveTimeBegin": keywords.taskArchiveTimeBegin=== undefined?null:keywords.taskArchiveTimeBegin,
                                "taskArchiveTimeEnd": keywords.taskArchiveTimeEnd=== undefined?null:keywords.taskArchiveTimeEnd,
                                "taskCreateTimeBegin": keywords.taskCreateTimeBegin=== undefined?null:keywords.taskCreateTimeBegin,
                                "taskCreateTimeEnd": keywords.taskCreateTimeEnd=== undefined?null:keywords.taskCreateTimeEnd,
                                "taskType": keywords.taskType=== undefined?'':keywords.taskType,
                                "taskUpdateTimeBegin": keywords.taskUpdateTimeBegin=== undefined?null:keywords.taskUpdateTimeBegin,
                                "taskUpdateTimeEnd": keywords.taskUpdateTimeEnd=== undefined?null:keywords.taskUpdateTimeEnd,
                                "loginCom": $$user.getUser().comCode || '',
                                "userCode":$$user.getUser().userCode
                            }
                        })
                            .success(function(data){
                                data = $$adapter.import('task',data);
                                if(data)
                                    deferred.resolve(data);
                                else
                                    deferred.reject('-1');
                            })
                            .error(function(e, code){
                                deferred.reject(code);
                            });
                        return deferred.promise;
                    },
                    /**
                     * @ngdoc
                     * @name $$cherry.$$finder#searchView
                     * @methodOf $$cherry.$$finder
                     *
                     * @description
                     * 视图查询
                     * @example
                     * $$finder.searchView(keywords,options);
                     * @param {Object()} keywords 视图查询条件
                     * @param {Object()} options 视图查询回调函数
                     * @returns {httpPromise} resolve with fetched data, or fails with error description.
                     */
                    searchView :function(keywords,options){
                        if(options.target === 'vehicle') {
                            $http({
                                method: 'POST',
                                dataType: "json",
                                contentType: 'application/json; charset=UTF-8',
                                url: config.backend.ip + config.backend.CarView,
                                headers: {},
                                data: {
                                    head:{
                                        "transCode": "CarView",
                                        "transType": "Req",
                                        "token": $$user.getUser().token
                                    },
                                    "vIN": keywords.vIN,
                                    "engine": keywords.engine,
                                    "plateNo": keywords.plateNo,
                                    "userCode": $$user.getUser().userCode,
                                    "loginCom": $$user.getUser().comCode
                                }
                            })
                                .success(function (data) {
                                    data = $$adapter.import('vehicle',data);
                                    options.onSuccess(data);
                                })
                                .error(function (e, code) {
                                    options.onError(code);
                                });
                        }
                        else{
                            $http({
                                method: 'POST',
                                dataType: "json",
                                contentType: 'application/json; charset=UTF-8',
                                url: config.backend.ip + config.backend.view,
                                headers: {},
                                data: {
                                    head:{
                                        "transCode": "UseBusiness",
                                        "transType": "Req",
                                        "token": $$user.getUser().token
                                    },
                                    "contractNo": keywords.contractNo|| keywords.contractNo1|| keywords.contractNo2,
                                    "businessType": keywords.businessType,
                                    "loginCom": $$user.getUser().comCode
                                }
                            })
                                .success(function (data) {
                                    var _data = angular.copy(data);
                                    data = $$adapter.import('proposal',data);
                                    data.head =_data.head;
                                    options.onSuccess(data);
                                })
                                .error(function (e, code) {
                                    options.onError(code);
                                });
                        }
                    },
                    /**
                     * @ngdoc
                     * @name $$cherry.$$finder#printList
                     * @methodOf $$cherry.$$finder
                     *
                     * @description
                     * 单证列表查询
                     * @example
                     * $$finder.printList(keywords,pagination,options);
                     * @param {Object()} keywords 单证列表查询条件
                     * @param {Object()} pagination 单证列表页数和每页多少页
                     * @param {Object()} options 单证列表询回调函数
                     * @returns {httpPromise} resolve with fetched data, or fails with error description.
                     */
                    //待打印列表--单证列表查询
                    printList:function(keywords,pagination,options){
                        $http({
                            method: 'POST',
                            dataType: "json",
                            contentType:'application/json; charset=UTF-8',
                            url: config.backend.ip + config.backend.printList,
                            headers: {
                            },
                            data:{
                                head:{
                                    "transCode": "DocumentsListQuery",
                                    "transType": "Res",
                                    "token":$$user.getUser().token
                                },
                                "pageNo":pagination.pageNo=== undefined?'':pagination.pageNo,
                                "rows":pagination.rows=== undefined?'':pagination.rows,
                                "proposalName": keywords.proposalName===undefined?'':keywords.proposalName,
                                "insuredName": keywords.insuredName===undefined?'':keywords.insuredName,
                                "plateNo": keywords.plateNo===undefined?'':keywords.plateNo,
                                "printFlag": keywords.printFlag===undefined?null:keywords.printFlag,
                                "VIN": keywords.VIN===undefined?'':keywords.VIN,
                                "businessType": keywords.businessType===undefined?'':keywords.businessType,
                                "contractNo": keywords.contractNo===undefined?'':keywords.contractNo,
                                "printStatus": keywords.printStatus===undefined?'':keywords.printStatus,
                                "startDate": keywords.startDate===undefined?'':keywords.startDate,
                                "endDate": keywords.endDate===undefined?'':keywords.endDate,
                                "engineNo": keywords.engineNo===undefined?'':keywords.engineNo,
                                "loginCom": $$user.getUser().comCode
                            }
                        })
                            .success(function(data){
                                data = $$adapter.import('printList',data);
                                options.onSuccess(data);
                            })
                            .error(function(e, code){
                                options.onError(code);
                            });
                    },
                    //暂时没有使用
                    noteQuery:function(NoteQuery){
                        noteQuery = {
                            data:[]
                        };
                        $http({
                            method: 'POST',
                            dataType: "json",
                            contentType:'application/json; charset=UTF-8',
                            url: config.backend.ip + config.backend.noteQuery,
                            headers: {},
                            data:{
                                head:{
                                    "transCode": "",
                                    "transType": "Res",
                                    "token":$$user.getUser().token
                                }

                            }
                        })
                            .success(function(data){
                                data = $$adapter.import('noteQuery',data);
                                noteQuery.data = data;
                            })
                            .error(function(e, code){

                            });
                        return noteQuery;
                    },
                    /**
                     * @ngdoc
                     * @name $$cherry.$$finder#searchCarModal
                     * @methodOf $$cherry.$$finder
                     *
                     * @description
                     * 车型查询
                     * @example
                     * $$finder.searchCarModal(CarModal，pagination);
                     * @param {Object()} CarModal 车型查询条件
                     * @param {Object()} pagination 车型查询页数和每页多少页
                     * @returns {httpPromise} resolve with fetched data, or fails with error description.
                     */
                    searchCarModal:function(CarModal,pagination){
                        CarModal = CarModal || {};
                        var deferred=$q.defer();
                        var _data ={
                            "head": {
                                "token": $$user.getUser().token,
                                "transType": "Req",
                                "transCode": "ModelsQuery"
                            },
                            "loginCom": $$user.getUser().comCode
                        };
                        _data.pageNo=pagination.pageNo || 1,
                            _data.rows=pagination.rows || 10,
                            _data.modelName=CarModal.modelName || '',
                            _data.modelCode=CarModal.modelCode || '',
                            _data. brand=CarModal.brand || '',
                            _data.carYear=CarModal.carYear || '',
                            _data.carKind=CarModal.carKind || '',
                            _data.deptCode=CarModal.deptCode || '',
                            _data.factory=CarModal.factory || '',
                            _data.series=CarModal.series || ''
                        _data.localModelCode=CarModal.localModelCode || ''
                        $http({
                            method: 'POST',
                            dataType: "json",
                            contentType:'application/json; charset=UTF-8',
                            url: config.backend.ip + config.backend.modelsQuery,
                            headers: {},
                            data:_data
                        })
                            .success(function(data){
                                data = $$adapter.import('searchCarModal',data);
                                if(data)
                                    deferred.resolve(data);
                                else{
                                    deferred.reject('-1');
                                }
                            })
                            .error(function(e, code){
                                deferred.reject(code);

                            });
                        return deferred.promise;
                    },
                    /**
                     * @ngdoc
                     * @name $$cherry.$$NB.$$vehicle#searchCarView
                     * @methodOf $$cherry.$$NB.$$vehicle
                     *
                     * @description
                     * 车视图查询
                     * @example
                     * $$vehicle.actualValue(carView,options);
                     * @param {Object()} carView 车视图查询条件
                     * @param {Object()} options 车视图回调函数
                     * @returns {httpPromise} resolve with fetched data, or fails with error description.
                     */
                    searchCarView:function(carView,options){
                        $http({
                            method: 'POST',
                            dataType: "json",
                            contentType:'application/json; charset=UTF-8',
                            url: config.backend.ip + config.backend.CarView,
                            headers: {},
                            data:{
                                head:{
                                    "TransCode":"CarView",
                                    "TransType":"Req",
                                    "token":$$user.getUser().token
                                },
                                "VIN": carView.VIN,
                                "engine": carView.engine,
                                "plateNo": carView.plateNo,
                                "loginCom": $$user.getUser().comCode,
                                "userCode": $$user.getUser().userCode
                            }
                        })
                            .success(function(data){
                                data = $$adapter.import('vehicle',data);
                                if(options && options.onSuccess)
                                    options.onSuccess(data);
                            })
                            .error(function(e, code){
                                if(options && options.onError)
                                    options.onError(code);
                            });
                    }
                };
            }])
});